package com.ygy.jxc;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt测试生成
 */
@SpringBootTest
public class Jwt {


    @Test
    void contextLoads() {
    }

    static String secret = "jxc";  //秘钥

    /**
     * 生成Token信息
     * ----------------
     *   head
     *   payload
     *   签名
     *   -----------------
     * eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
     * eyJleHAiOjE2NzgzNzAzNTUsInVzZXJpZCI6MTAwMX0.
     * hw20GkXU4e0LrQYaIqmz-onjfFcO9xWez5dcnLHwXFo
     */
    @Test
    void generatorToken(){
        Map<String,Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        Calendar calendar = Calendar.getInstance();   //日期
        calendar.add(Calendar.SECOND,60*60*24);
        String token = JWT.create()
                .withHeader(map) // 设置 header
                .withClaim("userid",1001) // 设置payload   用户id封装为token---解密后显示 value 1001
                .withExpiresAt(calendar.getTime()) // 设置过期时间 60秒
                .sign(Algorithm.HMAC256(secret)); // 设置签名 secret 秘钥 需要对外保密
        System.out.println(token);
    }

    /**
     * Token 的校验
     */
    @Test
    void verifier(){
        //上面生成的
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzgzNzAzNTUsInVzZXJpZCI6MTAwMX0.hw20GkXU4e0LrQYaIqmz-onjfFcO9xWez5dcnLHwXFo\n";
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();   //对应的算法HMAC256
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        System.out.println(decodedJWT.getClaim("userid").asInt());  //获取userid
    }

    /**
     * 加密
     */

}
